//
//  ZMComposeView.swift
//  ZMWeiboSwift
//
//  Created by pg on 2017/7/29.
//  Copyright © 2017年 pg. All rights reserved.
//

import UIKit
import pop

class ZMComposeView: UIView {

    //添加到控件中的所有的按钮的数组
    fileprivate lazy var composeButtonArray:[ZMMenuButton] = [ZMMenuButton]()
    //记录当前视图的父控制器
    var target: UIViewController?
    
    //懒加载菜单模型数组
    private lazy var composeMenuArray: [ZMComposeMenuModel] = {
        let modelArray = self.loadCopmosePlistData()
        
        return modelArray
    }()
    // 加载plist文件数据
    func loadCopmosePlistData()->([ZMComposeMenuModel]){
        
        //获取plist文件的路径
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)
        //根据路径读取文件内容
        let dicArray = NSArray(contentsOfFile: path!)!
        //使用yymodel将字典转成模型
        let composeMenuArray = NSArray.yy_modelArray(with: ZMComposeMenuModel.self, json: dicArray) as! [ZMComposeMenuModel]
        
        return composeMenuArray
        
    }
    
    //懒加载imageview 最为弹出视图的背景遮罩
    fileprivate lazy var coverImageView : UIImageView = {
        let image = UIImage.zm_getScreenShot().applyLightEffect()//获取当前屏幕的截图
        let imageview = UIImageView(image: image)
        return imageview
    }()
    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
        
      //  loadCopmosePlistData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func setupUI(){
    
        //设置当前view的size
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        //添加Imageview.y
        addSubview(coverImageView)
        //添加按钮
        addChildButton()
        //开启向上弹出动画
        startButtonAnimation(isUp: true)
    }
    
    func addChildButton(){
        
        //设置按钮的宽度
        let btnWidth : CGFloat = 80
        let btnHeight: CGFloat = 110
        let btnMargin: CGFloat = (ScreenWidth - 3*btnWidth)/4
        
        for i in 0..<self.composeMenuArray.count{
            //实例化按钮
            let btn = ZMMenuButton()
            btn.tag  = i
            btn.x = btnMargin + CGFloat(i%3) * (btnMargin + btnWidth)
            btn.y = btnMargin + CGFloat(i/3) * (btnMargin + btnHeight) + ScreenHeight
            btn.size = CGSize(width: btnWidth, height: btnHeight)
            
            
            
            let model = composeMenuArray[i]
            btn.setImage(UIImage(named:model.icon!), for: UIControlState.normal)
            btn.setTitle(model.title!, for: UIControlState.normal)
            btn.setTitleColor(UIColor.gray, for: UIControlState.normal)
            btn.titleLabel?.font = UIFont.systemFont(ofSize: 12)
            
            addSubview(btn)
            
            composeButtonArray.append(btn)
            
            //给按钮添加单击事件
            btn.addTarget(self, action: #selector(menuBtnClick(sender:)), for: UIControlEvents.touchUpInside)
            
        }
        
    }
    //MARK:- 单击按钮的事件
    func menuBtnClick(sender: ZMMenuButton) -> Void {
        
        //单击按钮要放大点击的按钮,同时缩小其他的按钮
        UIView.animate(withDuration: 0.5, animations: { 
            
            for (_,btn) in self.composeButtonArray.enumerated(){
                
                if btn == sender{
                    //点击按钮需要放大
                    btn.transform = CGAffineTransform(scaleX: 2, y: 2)
                }else{
                    //其余按钮全部缩小
                    btn.transform = CGAffineTransform(scaleX: 0.4, y: 0.5)
                }
                
                btn.alpha = 0.2
            }
            
        }) { (isfinish) in
            UIView.animate(withDuration: 0.5, animations: {
                
                for btn in self.composeButtonArray{
                    btn.alpha = 1.0
                    btn.transform = CGAffineTransform.identity
                }
            }, completion: { (isfinish) in
                //弹出点击按钮相对应的视图
                let model = self.composeMenuArray[sender.tag]
                              
                let classType = NSClassFromString(model.className!) as! UIViewController.Type
               
                let vc = classType.init()
                //创建导航控制器
                let nav = ZMNavController(rootViewController: vc)
                
                //弹出新控制器
                self.target?.present(nav, animated: true, completion: { 
                    //展示控制器完毕需要将本视图从父视图中移除
                    self.removeFromSuperview()
                })
                
                
            })
        }
        
    }
    
    func startButtonAnimation(isUp:Bool){
        
        
       var temparray = composeButtonArray
        if isUp == false{
            
          temparray = composeButtonArray.reversed()
        }
        
        
        for (i,btn) in temparray.enumerated(){
            //创建弹簧动画对象
            let animation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                
                //设置动画目标值
                animation?.toValue = CGPoint(x: btn.centerX, y: btn.centerY - 350 )
            }else{
                animation?.toValue = CGPoint(x: btn.centerX, y: btn.centerY + 350 )
            }
            
            //设置弹簧系数[0-20],系数越大弹簧震动幅度越大
            animation?.springBounciness = 20
            //设置初速度,默认值12 , [0-20]速度越大动画结束越快
            animation?.springSpeed = 12
            //设置动画开始时间
            animation?.beginTime = CACurrentMediaTime() +  Double(i) * 0.05
            //添加 并且开启动画
            btn.pop_add(animation, forKey: nil)
            
        }
    }
    
    //真实当前 的view   传递参数:表示要把当前view添加到哪个view上面显示
    func showComposeView(target: UIViewController){
        
        target.view.addSubview(self)
        //使用属性记录视图的父控制器
        self.target = target
    }
    
    
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        //执行向下的动画
        startButtonAnimation(isUp: false)
        //动画执行结束,移除遮罩视图
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) { 
            
            self.removeFromSuperview()
        }
        
    }
    

}
